const fs = require('fs')
const util = require('util')



/**
 *
	let readFile = promisify(fs.readFile);
	readFile('./name.txt', 'utf-8')
		.then(res => readFile(res, 'utf-8'))
		.then(res => readFile(res, 'utf-8'))
		.then(res => console.log(res))
 *
 */
 function callbackPromiseV5() {
 	var files = ['./resource/1.html','./resource/2.html','./resource/3.html']
 	var i = 0, content = '';
 	var readFile =  util.promisify(fs.readFile)

	// 内部包装了2个函数
	function buildContent (data, idx) {
		content += data 
		return readFile(files[idx], 'utf-8')
	}

	function co(promise, i, onFinished) {
		// 进入函数之后 先 ++i
		if(++i >= files.length) {
			return promise
		}
		// 将相同的代码再抽取一次， buildContent 每次都是返回一个promise
		var p = promise.then(data => buildContent(data, i))
		return co(p, i, onFinished)
	}

	var p = readFile(files[i], 'utf-8'); // 获取到promise对象进行链式调用
	co(p, i).then(data => {
		console.log('最后一次的链式调用:', data)
		console.log('-----------------------')
		console.log(content)
	})
}


// 迭代器的方案
function * callbackPromiseV6() { 
	var files = ['./resource/1.html','./resource/2.html','./resource/3.html']
	var i = 0, content = '';
	var readFile =  util.promisify(fs.readFile)
	
	let data1 = yield  readFile(files[i++], 'utf-8')
	content += data1
	
	let data2 = yield  readFile(files[i++], 'utf-8')
	content += data2

	let data3 = yield  readFile(files[i++], 'utf-8')
	content += data3

	return content
}


// 封装一个co模块
function co(it) {
	var result = [] ;
 
	return new Promise((resolve, reject) => {
		(function next(data) {
			let {value, done } = it.next(data)
			if(done) {
				// console.log(result)
				// console.log('-----------------------\n')
				
				return resolve(value)
			}
			value.then(data => {
				result.push(data)
				next(data)
			}, reject)
		})()
	})
}

// co(callbackPromiseV6()).then(value => {
// 	console.log(value)
// })


// 封装一个co模块
function coV2(it) {
	var result = [] ;
	return new Promise((resolve, reject) => {
		var res =  it.next()
		;(function wrap(res) {
			if(res.done) {
				// console.log(result)
				// console.log('-----------------------\n')
				return resolve(res.value)
			}
			res.value.then(data => {
				result.push(data)
				wrap(it.next(data))
			}, reject)
		})(res)
	})
}

coV2(callbackPromiseV6()).then(value => {
	console.log(value)
})



